<template>
  <div class="teach-plan">
    <div class="plan-status" v-if="classList.length > 0">
      <div
        :class="['plan-status-btn', {1:'status-success', 2: 'status-fail', 0:'status-normal'}[planStatus]]"
      >{{ filterStatus() }}</div>
      <el-button size="small" type="primary" @click="submitLesson">{{isEdit ? '提交':'编辑'}}</el-button>
    </div>
    <el-skeleton :loading="loading">
      <div class="class-times-container" v-if="classList.length">
        <draggable
          :modelValue="classList"
          @update:modelValue="dragSortHandle"
          :disabled="!isEdit"
          tag="transition-group"
          animation="250"
          item-key="sortNum"
        >
          <template #item="{ element, index }">
            <DataComponent
              @edit-lesson="setContent"
              @remove-lesson="removeLesson"
              :data="element"
              :index="index"
              :isEdit="isEdit"
              :key="index"
              :subjectId="subjectId"
              :oldData="classList[0]"
              :lessonType="data.type"
            />
          </template>
        </draggable>
      </div>
      <div class="content" v-else>
        <div class="tip">暂未设置教学计划,可以选择教学计划或直接上传文档备课</div>
        <div class="navigation">
          <div class="list">
            <img src="\src\assets\one-prepare\prepare-tip1.png" alt width="230" height="167" />
            <el-button @click="chiocePlan">选择标准教学计划</el-button>
          </div>
          <div class="list">
            <img src="/src/assets/one-prepare/prepare-tip2.png" alt width="230" height="167" />
            <el-button @click="chioceOtherPlan">选择其他学生教学计划</el-button>
          </div>
          <div class="list">
            <img src="/src/assets/one-prepare/prepare-tip3.png" alt width="230" height="167" />
            <el-button @click="directPrepare">批量添加课次</el-button>
          </div>
        </div>
      </div>
    </el-skeleton>
  </div>
</template>

<script lang="ts">
import { ref, watch, computed } from 'vue'
import draggable from 'vuedraggable'
import axios from 'axios'
import $ from '$'
import { ElMessage } from 'element-plus'
import store from '../store'
import DataComponent from './components/data.vue'
import ChiocePlanComponent from '@/views/one-prepare/prepare-edit/components/chioce-plan.vue'
import ChioceOtherPlanComponent from '@/views/one-prepare/prepare-edit/components/chioce-other-plan.vue'
export default {
  components: { DataComponent, draggable },
  props: {
    studentId: String,
    data: {
      type: Object,
      default: {},
    },
    searchType: {
      type: Number,
      default: '',
    },
  },
  setup(props) {
    let classList: any = ref([])
    let loading = ref(false)
    let isEdit = computed(() => store.state.editState)
    let planStatus = ref(0)
    let subjectId = ref('')
    $.emitter.emit('effect', (id) => (subjectId.value = id))
    let subjectName = ref()
    subjectName.value = $.storage.get('subject').name
    watch(isEdit, () => {
      store.commit('set_edit_state', isEdit.value)
    })
    const getTeachPlanClass = async () => {
      let res = await $.http.post('/admin/lessonTimes/queryContent', {
        lessonId: props.data.type ? props.data.lessonId : props.data.contractId,
      })
      if (res.result) {
        classList.value = res.json.map((ele, idx) => {
          ele.isRemove = false
          ele.sortNum = idx + 1
          return ele
        })
        // if (res.json.length > 0) {
        //   let subjectInfo = await $.http.post(`/admin/teachPlan/queryById`, {
        //     planId: res.json[0].planId,
        //   })
        //   subjectId.value = subjectInfo.json.subjectId
        // }
      }else {
        ElMessage.warning(res.msg)
      }
    }
    getTeachPlanClass()
    const queryPlanStatus = () => {
      let params = {}
      if (props.data.type) {
        params = {
          lessonId: props.data.lessonId,
          version: '',
        }
      } else {
        params = {
          lessonId: props.data.contractId,
          version: '',
        }
      }
      axios.post(`/admin/lessonTimesAudit/query`, params)
        .then((res: any) => {
          if (!res.result) return ElMessage.error(res.msg)
          planStatus.value = res.json.length > 0 ? res.json[0].status : 0
        })
    }
    queryPlanStatus()
    const dragSortHandle = async (list) => {
      classList.value = list.map((data, idx) => {
        {
          data.sortNum = idx + 1
          return data
        }
      })
    }
    const setContent = (data, index, isCreate) => {
      if ((data.id || classList.value[index] !== null) && !isCreate) {
        classList.value.splice(index, 1, data)
      } else {
        classList.value.forEach((ele) => {
          ele.sortNum >= index && (ele.sortNum += 1)
        })
        classList.value.push(data)
        classList.value = classList.value.sort((a, b) => {
          return a.sortNum - b.sortNum
        })
      }
    }
    const removeLesson = (index) => {
      classList.value.splice(index, 1)
    }
    const filterStatus = () => {
      return { 1: '审核通过', 2: '审核未通过', 0: '未审核' }[planStatus.value]
    }
    const submitLesson = async () => {
      let isHandout = classList.value.every(e => e.child)
      if (!isEdit.value) {
        store.commit('set_edit_state', !isEdit.value)
      } else {
        if (!isHandout) {
          ElMessage.warning('请为所有课次添加讲义！')
        } else {
          let saveRes = await $.http.json('/admin/lessonTimes/batchSaveForStudent', classList.value)
          if (saveRes.result) {
            store.commit('set_edit_state', !isEdit.value)
            ElMessage.success('保存成功！')
          } else {
            ElMessage.error(saveRes.msg)
          }
        }
      } 
    }
    const chiocePlan = () => {
      let title = $.element('div', {}, [
        $.element('span', {}, '选择教学计划课次添加'),
        $.element(
          'i',
          { style: { color: '#FF3D3D', fontSize: '14px' } },
          '（' + subjectName.value + ')'
        ),
      ])
      $.modal
        .create({
          title,
          width: 505,
          zIndex: 2015,
          bodyStyle: { padding: '0' },
          component: ChiocePlanComponent,
          props: { subjectId: subjectId.value },
        })
        .then((res) => {
          if (res) {
            store.commit('set_edit_state', true)
            classList.value = res[0].map((ele, i) => {
              ele.isRemove = true
              ele.lessonId = props.data.type ? props.data.lessonId : props.data.contractId,
              ele.lessonThirdId = null
              ele.id = null
              ele.sortNum = i + 1
              ele.status = 0
              return ele
            })
          }
        })
    }
    const chioceOtherPlan = () => {
      $.modal
        .create({
          title: '选择学生教学计划',
          width: 505,
          zIndex: 2015,
          bodyStyle: { padding: '0' },
          component: ChioceOtherPlanComponent,
          props: { subjectId: subjectId.value },
        })
        .then((res) => {
          if (res) {
            store.commit('set_edit_state', true)
            classList.value = res[0].map((ele, i) => {
              ele.isRemove = true
              ele.lessonId = props.data.type ? props.data.lessonId : props.data.contractId,
              ele.lessonThirdId = null
              ele.id = null
              ele.sortNum = i + 1
              ele.status = 0
              return ele
            })
          }
        })
    }
    const directPrepare = async () => {
      store.commit('set_edit_state', true)
      let nodes = [
        {
          label: '次数',
          type: 'number',
          key: 'sumTimes',
          min: 1,
          step: 1,
          strictly: true,
          rule: [{ required: true, message: '请输入次数' }],
        },
        {
          label: '课时',
          type: 'number',
          key: 'period',
          min: 1,
          step: 1,
          strictly: true,
          rule: [{ required: true, message: '请输入课时数' }],
          default: 2,
        },
      ]
      let formGroup = await $.modal.create({
        title: '批量添加',
        width: 400,
        zIndex: 2015,
        props: { nodes },
      })
      for (let i = 0; i < formGroup.sumTimes; i++) {
        classList.value.push({
          indexName: `第${i + 1}讲`,
          period: formGroup.period,
          lessonId: props.data.type ? props.data.lessonId : props.data.contractId,
          lessonThirdId: props.data.lessonThirdId,
          difficultPoint: '',
          sortNum: i + 1,
          status: 0,
          checked: 0,
          planId: null,
          id: null,
          handoutId: null,
          child: { handoutId: null },
          isRemove: true,
        })
      }
    }
    return {
      classList,
      getTeachPlanClass,
      queryPlanStatus,
      loading,
      dragSortHandle,
      isEdit,
      planStatus,
      filterStatus,
      setContent,
      removeLesson,
      submitLesson,
      subjectId,
      subjectName,
      chioceOtherPlan,
      chiocePlan,
      directPrepare,
    }
  },
}
</script>

<style scoped lang="scss">
.teach-plan {
  height: calc(100% - 60px);
  padding: 13px 30px;
  overflow: auto;
  position: relative;
  .plan-status {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
    .plan-status-btn {
      padding: 9px 12px 9px 26px;
      border-radius: 6px;
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      position: relative;
      cursor: pointer;
      &::before {
        content: '';
        height: 7px;
        width: 7px;
        position: absolute;
        left: 12px;
        top: calc(50% - 3px);
        border-radius: 50%;
      }
    }
    .status-success {
      border: 1px solid #37b2ab;
      color: #72b22a;
      background: rgba(26, 175, 167, 0.1);
      &::before {
        background-color: #72b22a;
      }
    }
    .status-fail {
      border: 1px solid #fc514f;
      color: #fc514f;
      background: #ffefeb;
      &::before {
        background: #fc514f;
      }
    }
    .status-normal {
      border: 1px solid #faad14;
      color: #faad14;
      background: #fff4df;
      &::before {
        background: #faad14;
      }
    }
    :deep(.el-button) {
      border-radius: 6px;
      padding: 6px 26px;
      font-size: 16px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
    }
  }

  .content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 0 70px;
    width: 100%;
    .tip {
      width: 500px;
      font-size: 30px;
      color: #333333;
      line-height: 42px;
      text-align: center;
      font-weight: 500;
      margin: 0 auto;
    }
    .navigation {
      margin-top: 50px;
      display: flex;
      justify-content: space-around;
      .list {
        display: flex;
        align-items: center;
        flex-direction: column;
      }
      button {
        margin-top: 40px;
        color: #72b22a;
        border: 1px solid #72b22a;
        &:hover {
          color: #fff;
          background: #72b22a;
        }
      }
    }
  }
}
</style>
